;(function($){
	$.jgrid.extend({
		initEditFormEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				//1.初始化控件事件
				if(grid.p.editFormSelector){
					var $editForm = $(grid.p.editFormSelector);
					//$editForm.data("isShowValidateMsg", true);
					var valChange = function(e){
						
						//if(!$.jqValidator.validateControl(e.target, null, false)){
							
							//$.jqValidator.showValidatePrompt($(e.target));
							//return false;
						//}
						
						var $target = $(e.target);
						var editingRowDataId = $editForm.find("input[name='"+grid.p.jsonReader.id+"']").val();
						if(editingRowDataId){
							//2.从正在被修改的数据
							var selRow = _this.jqGrid('getRowDataById',editingRowDataId);
							if(!$.isEmptyObject(selRow)){
								//3.表单中正在编辑的对象(convertSimpleForm2OrgObjectBySelector获取到表单中数据，日期不做转换)
								
								if($.jqValidator.validateForm(grid.p.editFormSelector) == false){
									return false;
								}
								var editingFormObj = FormUtils.convertSimpleForm2OrgObjectBySelector(grid.p.editFormSelector);
								//4.取到正在被修改的字段的值
								var propertyName = $target.attr("name");
								var propertyVal = $target.val();
								if($target.is('textarea')){
									propertyVal = $target.text();
								}else{
									propertyVal = $target.val();
								}
								//5.打包json对象时,值是true,false时不需要用引号
								if(propertyVal === true || propertyVal=="true" || propertyVal === false || propertyVal=="false"){
									$.extend(selRow,editingFormObj,$.parseJSON('{"'+propertyName+'":'+propertyVal+'}'));
								}else{
									$.extend(selRow,editingFormObj,$.parseJSON('{"'+propertyName+'":"'+propertyVal+'"}'));
								}
								//6.修改行状态
								if(selRow.rowStatus == Gfa.GlobalConstant.ROWSTATUS_UNCHANGED){
									$.extend(selRow,{rowStatus:Gfa.GlobalConstant.ROWSTATUS_MODIFIED});
								}else if(selRow.rowStatus == Gfa.GlobalConstant.ROWSTATUS_ADDED){
									$.extend(selRow,$.parseJSON("{\""+grid.p.jsonReader.id+"\":\""+editingRowDataId+"\"}"));
									$.extend(selRow,{rowStatus:Gfa.GlobalConstant.ROWSTATUS_ADDED});
								}
								//7.填充到表格
								_this.jqGrid('setRowData',editingRowDataId,selRow);
							}
						}
					}
					//编辑表单一旦开始编辑,必须开启信息提示
					$editForm.bind("keyup",function(){
						$.jqValidator.setIsShowValidateMsg(grid.p.editFormSelector,true);
					});
					$editForm.find("input:text").bind('blur',valChange)
						.end().find("input:radio").bind('click',valChange)
						.end().find("input:checkbox").bind('click',function(e){
							if(!$.browser.msie){
								var $target = $(e.target);
								var formatText = $target.attr("formatRules")
								var formatRules = $.parseJSON(formatText);
								if(formatText != null && formatRules.checkedValueMap != null){		
									if($('#'+$target.attr("id")+':checked').attr("checked")){
									//if($target.attr("checked") && ($target.attr("checked")===true || $target.attr("checked") =="true" || $target.attr("checked") == "checked")){
										$target.val(formatRules.checkedValueMap.checked)
									}else{
										$target.val(formatRules.checkedValueMap.unChecked)
									}
								}
								valChange(e);
							}else{
								valChange(e);
							}
						})
						.end().find("textarea").bind('blur',valChange)
						.end().find("select").bind('change',valChange);
				}
				//2.弹出编辑窗体
				if($.isPlainObject(grid.p.editWindow) && !$.isEmptyObject(grid.p.editWindow)){
					var $editWindow = $(grid.p.editWindow.selector);
					//弹出编辑窗体的默认按钮组
					var dialogDefaultButtons = [];
					
					//添加提交按钮
					if($.isEmptyObject(grid.p.editWindow.option) || grid.p.editWindow.option.showSubmitBtn == undefined || grid.p.editWindow.option.showSubmitBtn != false){
						dialogDefaultButtons.push({"text":$.jgrid.col.bSubmit,
							"click":function(){
								//确定前先验证
								if($.jqValidator.validateForm(grid.p.editFormSelector)){
									this.isSubmit = true;
									//关闭弹出层
									$.jqValidator.setIsShowValidateMsg(grid.p.editFormSelector,false);
									$(this).dialog("close");
								}
							}});
					}
					//添加取消按钮
					if($.isEmptyObject(grid.p.editWindow.option) || grid.p.editWindow.option.showCancelBtn == undefined || grid.p.editWindow.option.showCancelBtn != false){
						dialogDefaultButtons.push({"text":$.jgrid.col.bCancel,
							"click":function(){
								//关闭弹出层
								this.isCancle = true;
								$.jqValidator.setIsShowValidateMsg(grid.p.editFormSelector,false);
								$(this).dialog("close");
							}});
					}
					//添加自定义的按钮
					if(!$.isEmptyObject(grid.p.editWindow.option) && $.isArray(grid.p.editWindow.option.buttons) && grid.p.editWindow.option.buttons.length>0){
						for(var ob=grid.p.editWindow.option.buttons.length-1;ob>=0;ob--){
							dialogDefaultButtons.unshift(grid.p.editWindow.option.buttons[ob]);
						}
					}
					$editWindow.dialog($.extend({},$.ui.dialogDefaultConfig,grid.p.editWindow.option,{
						//取消Esc 关闭窗体功能(防止验证提示信息无法去除)
						closeOnEscape : true,
						//模式窗口
						modal:true,
						//自动打开
						autoOpen:false,
						//判断是否确认动作(扩展属性)
						isSubmit:false,
						//判断是否取消动作（扩展属性）
						isCancle:false,
						isFirstOpen:true,
						originalData:null,
						buttons:dialogDefaultButtons,
						open:function(event, ui){
							if(event.currentTarget.event.srcElement){
								if(event.currentTarget.event.srcElement.nodeName == "IMG"){
									this.isFirstOpen = false;
								}else{
									this.isFirstOpen = true;
								}
							}
							this.isSubmit = false;
							this.isCancle = false;
							var editingRowDataId = _this.jqGrid('getCurrentSelectRowId');
							this.originalData = _this.jqGrid('getRowDataById',editingRowDataId);
							if($.isFunction(grid.p.afterOpenEditWindow)){
								grid.p.afterOpenEditWindow.call(grid,event,ui);
							}
						},
						beforeClose : function(event, ui){
							if(this.isFirstOpen === false && this.isSubmit === false){
								var editingRowDataId = _this.jqGrid("getCurrentSelectRowId");
								_this.jqGrid("setRowData",editingRowDataId,this.originalData);
							}else if(this.isFirstOpen === true && this.isSubmit === false){
								//1.取消先将当前编辑的数据回复
								var editingRowDataId = $(grid.p.editFormSelector).find("input[name='"+grid.p.jsonReader.id+"']").val();
								_this.jqGrid('restoreRowDataByIds',[editingRowDataId]);
							}
							//2.屏蔽验证
							grid.p.enabledValidateForm = false;
							//4.刷新按钮状态
							_this.jqGrid('refreshButtonStatus');
							//3.必须先关闭校验规则的提示
							$.jqValidator.hideValidatePrompt4Form(grid.p.editFormSelector);
						},
						close : function(event,ui){
							//关闭编辑层后事件
							if($.isFunction(grid.p.afterCloseEditWindow)){
								grid.p.afterCloseEditWindow.call(grid,event,ui);
							}
							//关闭校验规则的提示
							$.jqValidator.setIsShowValidateMsg(grid.p.searchFormSelector,false);
						}
					}));
				}
			});
		},
		initSearchFormEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				//1.初始化控件事件
				if(grid.p.searchFormSelector){
					//2.初始化控件格式化规则
					$.jqFormatter.initFormatRules(grid.p.searchFormSelector);
					//3.初始化控件校验规则
					$.jqValidator.initValidateRules(grid.p.searchFormSelector);
					//4.打开校验规则的提示
					$.jqValidator.setIsShowValidateMsg(grid.p.searchFormSelector,true);
				}
			});
		},
		initSearchBtnEvent : function (){
			var grid = this[0],_this = this;
			return this.each(function(){
				var searchBtnId = grid.p.searchBtnId;
				if(grid.p.searchFormSelector && searchBtnId){
					$('#'+searchBtnId).bind('click',function(){
						//1.校验搜索区
						if(!$.jqValidator.validateForm(grid.p.searchFormSelector)){
							//alert("不通过.");
							return false;
						}
						
						//搜索前方法
						if($.isFunction(grid.p.beforeSearch)){
							if(!(grid.p.beforeSearch.call(grid))){
								return false;
							}
						}
						
						//2.将查询也重置为第一页
						grid.p.page = 1;
						//3.组装searchFrom 里的field,追加到grid 的queryInfo
						_this.jqGrid('setQueryInfoFields4Search',(Gfa.ConditionHelper.buildCondition(grid.p.searchFormSelector)));
						//alert($.objToJSONString(grid.p.postData));
						_this.jqGrid("reloadGrid");
					})
				}
			});
		},
		initNewBtnEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				if(grid.p.newBtnId){
					$('#'+grid.p.newBtnId).bind('click',function(){
						var newObj = {};
						var newIdVal = "newId_"+$.jgrid.global.newIdVal++;
						newObj = $.parseJSON("{\""+grid.p.jsonReader.id+"\":\""+newIdVal+"\",\"rowStatus\":"+Gfa.GlobalConstant.ROWSTATUS_ADDED+"}");
						
						//alert("是否验证："+grid.p.enabledValidateForm);
						//1.新增事件为跳转页 或 打开新tab(排除actionTarget配置的是 openEditWindow)
						if(!$.isEmptyObject(grid.p.newBtnActionConfig)){
							//如果newBtnActionConfig不为空,则以newBtnActionConfig配置的动作为准
							$.extend(grid.p.newBtnAction,grid.p.newBtnActionConfig);
						}
						if(!$.isEmptyObject(grid.p.newBtnAction)
								&& "openEditWindow" != grid.p.newBtnAction.actionTarget){
							//1.1.新增前方法
							if($.isFunction(grid.p.beforeNew)){
								if(!(grid.p.beforeNew.call(grid,newObj))){
									return false;
								}
							}
							//1.2.newBtnAction由"edit"列得到的配置,
							if($.isEmptyObject(grid.p.newBtnAction) || !$.isPlainObject(grid.p.newBtnAction)){
								grid.p.newBtnAction = {};
							}
							
							var url_html = App.ctx+grid.p.newBtnAction.actionUrl;
							if("self" == grid.p.newBtnAction.actionTarget){
								window.location.href = url_html;
							}else{
								window.parent.TabTagUtils.closeAndNewTab(grid.p.newBtnAction.tabId,grid.p.newBtnAction.tabTitle,url_html);
							}
						}else if(grid.p.cellEdit === true){//如果是表格内编辑
							//1.如果启用表格内编辑，需要恢复正在编辑的单元格到不可编辑状态
							_this.jqGrid("restoreCellStatus");
							//表格内编辑的校验
							if(!_this.jqGrid("validateCellDatas",_this.jqGrid("getSaveRowDatas"))){
								return false;
							}
							//将默认值对象 和新增 的对象合并
							$.extend(newObj,$.parseJSON("{\""+grid.p.jsonReader.id+"\":\""+newIdVal+"\",\"rowStatus\":\""+Gfa.GlobalConstant.ROWSTATUS_ADDED+"\"}"));
							//alert("通过.");
							//新增前方法
							if($.isFunction(grid.p.beforeNew)){
								if(!(grid.p.beforeNew.call(grid,newObj))){
									return false;
								}
							}
							//设置行数据在最前面
							_this.jqGrid("addRowData",newIdVal,newObj,"first");
							//去除其它行选中
							_this.jqGrid('resetSelection');
							//TODO:选中新增行 (会触发beforeSelectRow,onSelectRow 事件,
							//这样newIdVal就会赋值到表单的隐藏域中,编辑表单的数据才会赋值到grid中,
							//隐藏域的value如果是空,那么编辑表单数据就不会赋值到grid上)
							_this.jqGrid("setSelection",newIdVal,true);
							//新增后方法
							if($.isFunction(grid.p.afterNew)){
								grid.p.afterNew.call(grid,newObj);
							}
						}else{
							//2.执行验证
							if(grid.p.enabledValidateForm){
								if(!$.jqValidator.validateForm(grid.p.editFormSelector)){
									//alert("不通过.");
									return false;
								}
							}
							//3.先重置编辑区
							$.FormUtils.resetForm(grid.p.editFormSelector);
							//4.获取到编辑区的默认值
							var formObj = $.FormUtils.getFormNormalDataBySelector(grid.p.editFormSelector);
							//5.将默认值对象 和新增 的对象合并
							$.extend(newObj,formObj,$.parseJSON("{\""+grid.p.jsonReader.id+"\":\""+newIdVal+"\",\"rowStatus\":\""+Gfa.GlobalConstant.ROWSTATUS_ADDED+"\"}"));
							//alert("通过.");
							//6.新增前方法
							if($.isFunction(grid.p.beforeNew)){
								if(!(grid.p.beforeNew.call(grid,newObj))){
									return false;
								}
							}
							//7.设置行数据在最前面
							_this.jqGrid('addRowData',newIdVal, newObj,"first");
							//_this.jqGrid('setRowData',newIdVal,newObj);
							//8.去除其它行选中
							_this.jqGrid('resetSelection');
							//9.选中新增行 
							_this.jqGrid("setSelection",newIdVal,true);
							//10.如果有弹出层配置,就会弹出,否则不响应.
							_this.jqGrid("openEditWindow");
							//11.新增后方法
							if($.isFunction(grid.p.afterNew)){
								grid.p.afterNew.call(grid,newObj);
							}
							//12.新增时激活验证
							grid.p.enabledValidateForm = true;
						}
					})
				}
			});
		},
		initCancelBtnEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				if(grid.p.cancelBtnId){
					$('#'+grid.p.cancelBtnId).bind('click',function(){
						var ids = [];
						
						var cancelFunc = function(){
							if(grid.p.cellEdit === true){
								//回复数据
								for(var i=0;i<ids.length;i++){
									_this.jqGrid('restoreRow',ids[i]);
								}
							}
							//将数据回复
							_this.jqGrid('restoreRowDataByIds',ids);
							//清空编辑表单
							$(grid.p.editFormSelector).trigger("reset");
							//取消所有选择行的状态
							_this.jqGrid('resetSelection');
							//屏蔽验证
							grid.p.enabledValidateForm = false;
							//取消后方法
							if($.isFunction(grid.p.afterCancel)){
								grid.p.afterCancel.call(grid);
							}
							//表格内编辑需要重置一下"行列"坐标,和最新选中行
							if(grid.p.cellEdit === true){
								grid.p.iRow = -1;
								grid.p.iCol = -1;
								grid.p.selrow = "";
							}
						}
						
						//取消全部
						if(grid.p.cancelDataScope == "all"){
							ids = _this.jqGrid('getDataIDs');
							//取消前方法
							if($.isFunction(grid.p.beforeCancel)){
								if(!(grid.p.beforeCancel.call(grid,ids))){
									return false;
								}
							}
							//确认取消全部
							var imgUrl = "<img src='"+App.ctx+"/scripts/widgets/jquery-ui/extend/images/icon-question.gif'/>";
							$("<div id='"+grid.p.id+"EditWindow'>").attr('title',$.jgrid.nav.alertcap).html(imgUrl+" "+$.jgrid.warning.cancelAll).dialog({
								modal:true,
								height:200,
								resizable:false,
								show:$.ui.effects.dialog.show,
								hide:$.ui.effects.dialog.hide,
								buttons:[
								    {"text":$.jgrid.col.bSubmit,
									"click":function(){
										cancelFunc();
										$(this).dialog("close");
									}},
									{"text":$.jgrid.col.bCancel,
									"click":function(){
										$(this).dialog("close");
									}}
								]
							});
						}else{
							//不允许多行选中时,取当前选中行
							if(!grid.p.multiselect){
								ids[0] = _this.jqGrid('getGridParam','selrow');
							}else{
								ids = _this.jqGrid('getGridParam','selarrrow');
							}
							//取消前方法
							if($.isFunction(grid.p.beforeCancel)){
								if(!(grid.p.beforeCancel.call(grid,ids))){
									return false;
								}
							}
							if(ids.length < 1){
								$.ui.dialog4Prompt($.jgrid.prompt.selectCancel);
								return;
							}
							cancelFunc();
						}
						//按钮状态
						_this.jqGrid('refreshButtonStatus');
						//关闭校验规则的提示
						$.jqValidator.setIsShowValidateMsg(grid.p.editFormSelector,false);
						//去除验证样式
						$.jqValidator.hideValidatePrompt4Form(grid.p.editFormSelector);
					})
				}
			});
		},
		initResetBtnEvent : function(){
			var grid = this[0];
			return this.each(function(){
				if(grid.p.resetBtnId && grid.p.editFormSelector){
					$('#'+grid.p.resetBtnId).bind('click',function(){
						$.FormUtils.resetForm(grid.p.editFormSelector);
					})
				}
			});
		},
		initClearBtnEvent : function(){
			var grid = this[0];
			return this.each(function(){
				if(grid.p.clearBtnId && grid.p.searchFormSelector){
					$('#'+grid.p.clearBtnId).bind('click',function(){
						$.FormUtils.resetForm(grid.p.searchFormSelector);
					})
				}
			});
		},
		initSaveBtnEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				if(grid.p.saveBtnId){
					$('#'+grid.p.saveBtnId).bind('click',function(){
						//立即刷新按钮状态(防止重复点击)
						_this.jqGrid('refreshButtonStatus');
						_this.jqGrid("saveGridDatas");
					})
				}
			});
		},
		initDeleteBtnEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				if(grid.p.deleteBtnId){
					var $deleteBtn = $('#' +grid.p.deleteBtnId);
					
					$deleteBtn.attr("disabled",true);
					$deleteBtn.bind('click',function(){
						//如果启用表格内编辑，需要恢复正在编辑的单元格到不可编辑状态
						_this.jqGrid("restoreCellStatus");
						var editData = _this.jqGrid("getRowDatasByDelete");
						if(editData.length < 1){
							//如果选中的数据中有“新增”状态的数据，要重新刷新一下按钮状态
							_this.jqGrid('refreshButtonStatus');
							return;
						}
						//删除数据
						_this.jqGrid("deleteRows",editData);
						//按钮状态
						_this.jqGrid('refreshButtonStatus');
					})
				}
			});
		},
		initResizeEvent : function(){
			var grid = this[0],_this = this;
			return this.each(function(){
				if(grid.p.enableResize){
					window.onresize = function(){
						_this.jqGrid("resetGridWidth",true);
					}
				}
			});
		}
	});
})(jQuery);